package ext.tianma.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.core.meta.common.TypeIdentifierHelper;
import com.ptc.windchill.enterprise.copy.server.CoreMetaUtility;

import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTValuedHashMap;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleState;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.ownership.Ownership;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.pdmlink.PDMLinkProduct;
import wt.pom.Transaction;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfVariable;

/**
* 上传的文档自动创建为文档对象 存放在所选产品库的指定文件夹{设计类文档}下
* 
* @author 29036
* 
*/
public class CreateDocAndDescribeLink implements RemoteAccess {
	public static String FOLDER = "/Default"; // 创建文件夹
	public static String DOCTYPE = "";
	public static String secFolder = "/设计类文档";

	public static void main(String[] args) throws Exception {
		RemoteMethodServer rms = RemoteMethodServer.getDefault();
		rms.setUserName("wcadmin");
		rms.setPassword("tmadmin");
	}

	public static WTDocument createDocAndLink(Object primaryContent,
			String name, String oid, String wid, String docKey, String con)
			throws Exception {
		System.out.println("===1111111===>>");
		WfProcess process = (WfProcess) MyUtil.getObjectByOid(wid);
		WTDocument doc = (WTDocument) process.getContext().getValue(docKey);
		if (doc == null) {
			doc = createDoc(primaryContent, name, con, docKey, wid);
			System.out.println("===docKey===>>"+docKey);
			WTPart part = (WTPart) MyUtil.getObjectByOid(oid);
			System.out.println("===part===>>"+part);
			CreateDocAndDescribeLink.createDesLink(part, doc);
			System.out.println("doc====>>"+doc.getNumber());
			WfVariable VariableMainType = process.getContext().getVariable(docKey);
			VariableMainType.setValue(doc);
		    process = (WfProcess)wt.fc.PersistenceHelper.manager.save (process);
		} else {
			File file = (File) primaryContent;
			InputStream io = new FileInputStream(file);
			replacePrimaryContent(doc, io, file.getName());
		}
		return doc;
	}

	public static WTDocument createDocAndLink2(Object primaryContent,
			String name, String oid, String wid, String docKey, String con)
			throws Exception {
		System.out.println("===2222===>>");
		WfProcess process = (WfProcess) MyUtil.getObjectByOid(wid);
		WTDocument doc = (WTDocument) process.getContext().getValue(docKey);
		if (doc == null) {
			doc = createHBDoc(primaryContent, name, con, docKey, wid);
			System.out.println("===docKey===>>"+docKey);
			WTPart part = (WTPart) MyUtil.getObjectByOid(oid);
			System.out.println("===part===>>"+part);
			CreateDocAndDescribeLink.createDesLink(part, doc);
			System.out.println("doc====>>"+doc.getNumber());
		    process = (WfProcess)wt.fc.PersistenceHelper.manager.save (process);
		} else {
			File file = (File) primaryContent;
			InputStream io = new FileInputStream(file);
			replacePrimaryContent(doc, io, file.getName());
		}
		return doc;
	}

	/**
	 * 为上传文档创建文档对象
	 * 
	 * @param name
	 * @param partNumber
	 * @return
	 * @throws Exception
	 */
	public static WTDocument createDoc(Object primaryContent, String name,
			String con, String docKey, String wid) throws Exception {
		WTDocument doc = WTDocument.newWTDocument();
		WTContainer container = null;
		boolean access = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction trx = new Transaction();
		try {
			trx.start();
			QueryResult qr = MyUtil.getQueryResult(WTContainer.class,
					WTContainer.NAME, con);
			while (qr.hasMoreElements()) {
				container = (WTContainer) qr.nextElement();
			}
			// 获取容器的引用
			WTContainerRef containerRef = WTContainerRef
					.newWTContainerRef(container);
			PDMLinkProduct product = (PDMLinkProduct) containerRef.getObject();
			doc.setContainer(product);

			// 设置文件夹
			Folder location = null;
			// 查询文件夹是否存在
			try {
				location = FolderHelper.service.getFolder(FOLDER + secFolder,
						containerRef);
			} catch (Exception e) {
				location = null;
			}
			// 若文件夹不存在，则创建该文件夹
			if (location == null)
				location = FolderHelper.service.saveFolderPath(FOLDER
						+ secFolder, containerRef);
			// 设置文件夹到Doc对象
			if (location != null) {
				WTValuedHashMap map = new WTValuedHashMap();
				map.put(doc, location);
				FolderHelper.assignLocations(map);
			}

			// 设置文档名和存放位置
			doc.setName(name);
			//设置文档所有者
			doc.setOwnership(Ownership.newOwnership(SessionHelper.manager
					.getPrincipal()));
			Folder folder = FolderHelper.service.getFolder(FOLDER + secFolder,
					containerRef);
			FolderHelper.assignLocation((FolderEntry) doc, folder);

			// 设置文档类型
			if(docKey.equals("appDoc")){
				DOCTYPE = "cn.tianma.Acknowledgment";
			} else if(docKey.equals("safeDoc")){
				DOCTYPE = "cn.tianma.EnvSafeDocument";
			} else{
				DOCTYPE = "cn.tianma.PartsApprovalReport";
			}
			TypeIdentifier id = TypeIdentifierHelper.getTypeIdentifier(DOCTYPE);
			doc = (WTDocument) CoreMetaUtility.setType(doc, id);
			doc = (WTDocument) PersistenceHelper.manager.save(doc);
			doc = (WTDocument) PersistenceHelper.manager.refresh(doc);
			ApplicationData appData = ApplicationData.newApplicationData(doc);
			appData.setRole(ContentRoleType.PRIMARY);
			appData = (ApplicationData) PersistenceHelper.manager.save(appData);
			
			// 设置主内容
			if (primaryContent != null) {

				if (primaryContent instanceof File) {
					File file = (File) primaryContent;
					if (file.exists()) {
						appData.setFileName(file.getName());
						appData.setUploadedFromPath(file.getAbsolutePath());
						appData = ContentServerHelper.service.updateContent(
								doc, appData, file.getAbsolutePath());
					}
				} else if (primaryContent instanceof InputStream) {
					InputStream ins = (InputStream) primaryContent;
					appData = ContentServerHelper.service.updateContent(doc, appData, ins);
				}
			}

			// 设置文档状态（正在审阅）
			State state = State.toState("UNDERREVIEW");
			LifeCycleState cycleState = LifeCycleState.newLifeCycleState();
			cycleState.setState(state);
			doc.setState(cycleState);
			doc = (WTDocument) PersistenceServerHelper.manager.restore(doc);
								
			trx.commit();
			trx = null;				
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (trx != null) {
				trx.rollback();
			}
			SessionServerHelper.manager.setAccessEnforced(access);
		}
		return doc;
	}

	
	
	/**
	 * 为上传文档创建环保文档对象
	 * 
	 * @param name
	 * @param partNumber
	 * @return
	 * @throws Exception
	 */
	public static WTDocument createHBDoc(Object primaryContent, String name,
			String con, String docKey, String wid) throws Exception {
		WTDocument doc = WTDocument.newWTDocument();
		WTContainer container = null;
		boolean access = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction trx = new Transaction();
		try {
			trx.start();
			QueryResult qr = MyUtil.getQueryResult(WTContainer.class,
					WTContainer.NAME, con);
			while (qr.hasMoreElements()) {
				container = (WTContainer) qr.nextElement();
			}
			// 获取容器的引用
			WTContainerRef containerRef = WTContainerRef
					.newWTContainerRef(container);
			PDMLinkProduct product = (PDMLinkProduct) containerRef.getObject();
			doc.setContainer(product);

			// 设置文件夹
			Folder location = null;
			// 查询文件夹是否存在
			try {
				location = FolderHelper.service.getFolder(FOLDER + secFolder,
						containerRef);
			} catch (Exception e) {
				location = null;
			}
			// 若文件夹不存在，则创建该文件夹
			if (location == null)
				location = FolderHelper.service.saveFolderPath(FOLDER
						+ secFolder, containerRef);
			// 设置文件夹到Doc对象
			if (location != null) {
				WTValuedHashMap map = new WTValuedHashMap();
				map.put(doc, location);
				FolderHelper.assignLocations(map);
			}

			// 设置文档名和存放位置
			doc.setName(name);
			Folder folder = FolderHelper.service.getFolder(FOLDER + secFolder,
					containerRef);
			FolderHelper.assignLocation((FolderEntry) doc, folder);

			// 设置文档类型
			if(docKey.equals("appDoc")){
				DOCTYPE = "cn.tianma.EnvironmentalDocument";
			} else if(docKey.equals("safeDoc")){
				DOCTYPE = "cn.tianma.EnvSafeDocument";
			} else{
				DOCTYPE = "cn.tianma.EnvironmentalDocument";
			}
			TypeIdentifier id = TypeIdentifierHelper.getTypeIdentifier(DOCTYPE);
			doc = (WTDocument) CoreMetaUtility.setType(doc, id);
			doc = (WTDocument) PersistenceHelper.manager.save(doc);
			doc = (WTDocument) PersistenceHelper.manager.refresh(doc);
			ApplicationData appData = ApplicationData.newApplicationData(doc);
			appData.setRole(ContentRoleType.PRIMARY);
			appData = (ApplicationData) PersistenceHelper.manager.save(appData);
			
			// 设置主内容
			if (primaryContent != null) {

				if (primaryContent instanceof File) {
					File file = (File) primaryContent;
					if (file.exists()) {
						appData.setFileName(file.getName());
						appData.setUploadedFromPath(file.getAbsolutePath());
						appData = ContentServerHelper.service.updateContent(
								doc, appData, file.getAbsolutePath());
					}
				} else if (primaryContent instanceof InputStream) {
					InputStream ins = (InputStream) primaryContent;
					appData = ContentServerHelper.service.updateContent(doc, appData, ins);
				}
			}

			// 设置文档状态（正在审阅）
			State state = State.toState("UNDERREVIEW");
			LifeCycleState cycleState = LifeCycleState.newLifeCycleState();
			cycleState.setState(state);
			doc.setState(cycleState);
			doc = (WTDocument) PersistenceServerHelper.manager.restore(doc);
								
			trx.commit();
			trx = null;				
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (trx != null) {
				trx.rollback();
			}
			SessionServerHelper.manager.setAccessEnforced(access);
		}
		return doc;
	}


	/**
	 * 上传文档与物料建立关联关系
	 * 
	 * @param part
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	public static WTPartDescribeLink createDesLink(WTPart part, WTDocument doc)
			throws Exception {
		WTPartDescribeLink link = WTPartDescribeLink.newWTPartDescribeLink(
				part, doc);
		PersistenceServerHelper.manager.insert(link);
		return link;
	}

	

	/**
	 * 更新主内容或附件
	 * 
	 * @param holder
	 * @param in
	 * @param name
	 * @param type
	 */
	public static void updateContent(ContentHolder holder, InputStream in,
			String name, ContentRoleType type) {

		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction trx = new Transaction();

		try {
			trx.start();
			PersistenceServerHelper.manager.lock(holder);
			ApplicationData data = ApplicationData.newApplicationData(holder);
			data.setRole(type);
			data.setFileName(name);
			data = ContentServerHelper.service.updateContent(holder, data, in);
			trx.commit();
			trx = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (trx != null) {
				trx.rollback();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}

	/**
	 * 更新主内容
	 * @param holder
	 * @param in
	 * @param name
	 */
	public static void replacePrimaryContent(ContentHolder holder,
			InputStream in, String name) {
		try {
			QueryResult qr = ContentHelper.service.getContentsByRole(holder,
					ContentRoleType.PRIMARY);

			while (qr.hasMoreElements()) {
				ApplicationData oAppData = (ApplicationData) qr.nextElement();
				ContentServerHelper.service.deleteContent(holder, oAppData);
			}

			updateContent(holder, in, name, ContentRoleType.PRIMARY);
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}
	
	
	
	/*public static WfActivity getActByProcess(WfProcess process) throws WfException, WTException {
		List<WorkItem> workItem = MyUtil.getWorkItem(process);
		WfActivity wfactivity1 = null;
		System.out.println("---------workItem-------"+workItem.size());
		for(int i=0; i<workItem.size(); i++) {
			WorkItem item = workItem.get(i);
			WfActivity wfactivity2 = (WfActivity) item.getSource().getObject();
			if(wfactivity2.getName().equals("样品提交")){
				wfactivity1 = wfactivity2;
				System.out.println("---------activity2-------"+wfactivity2);
			}
		}
		System.out.println("---------activity1-------"+wfactivity1);
		System.out.println("---------activity1-------"+wfactivity1.getName());
		return wfactivity1;
		
	}*/

}

